package com.crayon.account.loader;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.AsyncTaskLoader;

import com.crayon.account.dao.DAOAccount;
import com.crayon.account.dao.DataBaseManager;
import com.crayon.account.data.EDAType;
import com.crayon.account.data.ENMapKey;
import com.crayon.util.GDB;
import com.crayon.util.UTILDate;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;

import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.PeriodList;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.Recur;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.property.RRule;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class LoaderSQLAccountBetween extends AsyncTaskLoader<HashMap<ENMapKey, Object>> {


	Date dtStart;
	Date dtEnd;
	boolean isReflected = true;

	public LoaderSQLAccountBetween(Context context,Date dtStart,Date dtEnd, Bundle bundle) {
		super(context);
		this.dtStart = dtStart;
		this.dtEnd = dtEnd;
	}

	@Override
	public HashMap<ENMapKey, Object> loadInBackground() {
		HashMap<ENMapKey, Object> hashMap =new HashMap<ENMapKey, Object>();
		DataBaseManager baseManager =DataBaseManager.getHelper(getContext());
		List<DAOAccount> daoAccounts =new LinkedList<DAOAccount>();
		hashMap.put(ENMapKey.DAOLISTARRAY, daoAccounts);
		long priceTotal=0;
		long priceIncom=0;
		long priceOutcom=0;
		List<DAOAccount> list=null;
		try {

			Dao<DAOAccount, Integer> daoAccount =baseManager.getDAOAccount();
			QueryBuilder<DAOAccount, Integer> builder = daoAccount.queryBuilder();
			Where<DAOAccount, Integer> where = builder.where();
			GDB.log(getClass(), "AccountSQL #### Dtstart\t" + UTILDate.getYYYYMDDHHMMSS(dtStart) +"\tDtEnd=" +UTILDate.getYYYYMDDHHMMSS(dtEnd));
			where.and(where.between("dtStart", dtStart, dtEnd)
					,where.lt("dtEnd", dtEnd)
					,where.isNull("recur")
					);
            GDB.log(getClass(), "SQL " + where.getStatement());
			list= where.query();
			
			//
			where.clear();
			where.isNotNull("recur");//					where.lt("dtUntil", dtEnd)
			list.addAll(where.query());
			GDB.log(getClass(), "SQL list  " + list.size());
			
		}catch(Exception e ){
            GDB.log(getClass(), "SQL err   " + e.getMessage());
        }

		
        for(DAOAccount ical : list){
            VEvent event = new VEvent(new DateTime(ical.getDtStart().getTime()),new DateTime(ical.getDtEnd().getTime()),ical.getSummary());
            if(ical.getRecur()!=null){
                try {
                    Recur recur = new Recur(ical.getRecur());
                    GDB.log(getClass(), "recurl " + recur.toString());
                    event.getProperties().add(new RRule(recur));
                } catch (Exception e) {
                    // TODO: handle exception
                    GDB.log(getClass(), "err 반목 데이타 추가 오류 " + e.getMessage());

                }
                try {
                    PropertyList exlist = ical.getExDateList();
                    if(exlist!=null && exlist.size()>0){
                        event.getProperties().addAll(exlist);
                    }
//
                } catch (Exception e) {
                    // TODO: handle exception
                    GDB.log(getClass(), "err exdate 예외 일자 추가 시 오류 발생 " + e.getMessage());
                }
            }
            try{
                Period period = new Period(new net.fortuna.ical4j.model.DateTime(dtStart.getTime()), new net.fortuna.ical4j.model.DateTime(dtEnd.getTime()));
//					period.setTimeZone(UTILDate.getTimeZoneDateTime());
                GDB.log(getClass(), "기간 조회 기간 시작일 " + period.getStart() +"\t 기간종료일 : " + period.getEnd());
//					PeriodList periodList = event.calculateRecurrenceSet(period);
                PeriodList periodList = event.getConsumedTime(new net.fortuna.ical4j.model.DateTime(dtStart.getTime()), new net.fortuna.ical4j.model.DateTime(dtEnd.getTime()));
                for (Object po : periodList) {
                    Period item  = (Period)po;
                    GDB.log(getClass(), "item date "  +"\t" + item.getStart() +"\t" + item.getEnd() +"\tprice" + ical.getXprice());
                    DAOAccount icalCron = ical.createCron();
                    icalCron.setDtStart(new Date(item.getStart().getTime()));
                    icalCron.setDtEnd(new Date(item.getEnd().getTime()));
                    if(ical.getXprice()>0){
                        if(ical.getxIOType()==EDAType.INCOM.getKey()
                                ||ical.getxIOType()==EDAType.FIXEDINCOM.getKey()
                                ){
                            priceTotal+=ical.getXprice();
                            priceIncom+=ical.getXprice();
                        }else if(ical.getxIOType()==EDAType.OUTCOM.getKey()
                                ||ical.getxIOType()==EDAType.FIXEDOUTCOM.getKey()
                                ){
                            priceTotal-=ical.getXprice();
                            priceOutcom+=ical.getXprice();
                        }
                    }
                    daoAccounts.add(icalCron);
                }

            }catch(Exception e){
                GDB.log(getClass(), "err 데이타 vent 기간조회시 오류 " + e.getMessage());
            }

        }
				

//		} catch (Exception e) {
//			GDB.log(getClass(), "SQL ERR" + e.getMessage());
//		}

		hashMap.put(ENMapKey.TOTALSUMMARY, priceTotal);
		hashMap.put(ENMapKey.TOTALINCOM, priceIncom);
		hashMap.put(ENMapKey.TOTALOUTCOM, priceOutcom);
		hashMap.put(ENMapKey.DATE_START, dtStart.getTime());
		
		GDB.log(getClass(), "총 합계" + priceTotal);
		GDB.log(getClass(), "총 수입" + priceIncom);
		GDB.log(getClass(), "총 지출" + priceOutcom);

//        if(list==null || list.size()<=0){
//            Dao<DAOAccount, Integer> daoAccount =baseManager.getDAOAccount();
//
//        }

		return hashMap;
	}

	/**
	 * @mail wonsork@gmail.com
	 * @writter WONSORK KIM
	 */
	@Override
	protected void onStartLoading() {
		// TODO Auto-generated method stub
		super.onStartLoading();
		forceLoad();
	}

}


